package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import top.littlejiang.onlinexam.common.base.BusinessException;
import top.littlejiang.onlinexam.common.utils.RedisUtils;
import top.littlejiang.onlinexam.entity.OlexamExam;
import top.littlejiang.onlinexam.entity.OlexamExamWork;
import top.littlejiang.onlinexam.entity.OlexamUser;
import top.littlejiang.onlinexam.mapper.OlexamExamWorkMapper;
import top.littlejiang.onlinexam.service.OlexamExamWorkService;
import top.littlejiang.onlinexam.service.OlexamUserService;
import top.littlejiang.onlinexam.websocket.common.WsConstant;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 考试工作关系表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2021-03-14
 */
@Service
public class OlexamExamWorkServiceImpl extends BaseServiceImpl<OlexamExamWorkMapper, OlexamExamWork> implements OlexamExamWorkService {

    @Autowired
    OlexamUserService userService;

    /**
     * 根据考试uuid 删除
     *
     * @param uuids
     */
    @Override
    public void deleteByUuid(List<String> uuids) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("fk_exam_uuid", uuids);
        this.baseMapper.delete(wrapper);
    }

    /**
     * 根据用户查询考试
     *
     * @param work
     * @return
     */
    @Override
    public List<OlexamExam> selectByUser(OlexamExamWork work) {
        if (Objects.isNull(work.getFkUserId())){
            throw new BusinessException("查询条件错误");
        }

        List<OlexamExam> exams = baseMapper.getExamByUser(work);
        return exams;
    }

    /**
     * 获取 进入考试的学生列表 userIds
     *
     * @param examUuid
     * @return
     */
    @Override
    public List<OlexamUser> getStudents(String examUuid) {
        Set<String> studentIds = RedisUtils.hkeys(WsConstant.STUDENT_PREFIX + examUuid);
        if (CollectionUtils.isEmpty(studentIds)){
            return null;
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id,user_name,user_account");
        wrapper.eq("is_del", 0);
        wrapper.in("id", studentIds);
        List<OlexamUser> list = userService.list(wrapper);

        return list;
    }
}
